
<style> 
#efence_list{ position:absolute; left:0px; top:0px; background:#FFFFFF; width:400px;height:98% }
#efence_tool { position:absolute; left:420px; top:10px; background:#FFFFFF; width:50%;}
</style> 

<div id="allmap" class ="baidu-maps" style="width: 100%;height: 100%"></div>
  <div id="efence_list" style="margin: 0;padding: 5px;">
    <!-- 围栏列表开始 -->
    <!-- 隐藏设备栏 -->
    <i style="position: absolute;right: 0" class="layui-icon layui-icon-close" onclick="dev_panle_sw('hide')"></i>
    <form class="layui-form layui-form-pane" action="" style="width:auto;height: 15px;padding: 5px;">
      <div class="layui-form-item">
          <div class="layui-inline" >
              <div class="layui-input-inline" style="width: 280px">
                  <input type="text"  name="search_key"  placeholder="输入围栏名称,查找围栏详情" autocomplete="off" class="layui-input" style="height: 30px;">
              </div>
              <div class="layui-form-mid layui-word-aux"></div>
              <a type="button" class="layui-btn layui-btn-sm" lay-submit="" lay-filter="data-search-btn" >搜索</a>
          </div>
      </div>
    </form>
  <table id="efence_list_table" class="layui-table" lay-filter="efence_list_table"></table>
  <!-- 围栏列表结束 -->
  <!-- 单个设备绑定的围栏列表开始 -->
  <form class="layui-form layui-form-pane" action="" style="width:auto;height: 15px;padding: 5px;">
    <div class="layui-form-item">
        <div class="layui-inline" >
            <div class="layui-input-inline" style="width: 280px">
                <input type="text"  name="search_key"  placeholder="输入设备名称/ID,查找设备绑定围栏" autocomplete="off" class="layui-input" style="height: 30px">
            </div>
            <div class="layui-form-mid layui-word-aux"></div>
            <a type="button" class="layui-btn layui-btn-sm" lay-submit="" lay-filter="dev-efe-search-btn" >搜索</a>
        </div>
    </div>
  </form>
  <table id="efence_of_dev_table" class="layui-table" lay-filter="efence_of_dev_table"></table>
  <!-- 单个设备绑定的围栏列表结束 -->
</div>

<!-- 设备栏展示按钮 -->
<button id="show_sw" class="layui-btn" onclick="dev_panle_sw('show')" style="position: absolute;left:-20px;top: 40%;height: 150px;width: 10px;display: none;"><i class="layui-icon">&#xe66b;</i></button>

<script type="text/html" id="draw_efence">
    <a class="layui-btn layui-btn-sm" lay-event="draw_efence" style="display: none;">新建</a>
</script>

<div id="efence_tool" style="color:white;background-color:rgba(320,138,138,0)">
  <div class="layui-form-item">
    <div class="layui-inline" >
       <div class="layui-input-inline">
          <button class="layui-btn layui-btn-sm" id="reset_efence">重置围栏</button>
       </div>
    </div>
    <div class="layui-inline" >
        <div class="layui-input-inline">
            <input type="text"  id="search_address"  placeholder="搜索地址" autocomplete="off" class="layui-input" style="height: 30px">
        </div>
        <div class="layui-form-mid layui-word-aux"></div>
        <a type="button" class="layui-btn layui-btn-sm" onclick="search_map($('#search_address').val())">搜索</a>
    </div>
  </div>
</div>
<!-- 围栏设置表格开始 -->

<form  class="layui-form layui-form-pane " id="handle_data_form" action=""  lay-filter="handle_data_form" style="display: none;padding: 10px">
    <div class="layui-form-item">
      <div class="layui-inline">
        <label class="layui-form-label layui-bg-green">围栏名称</label>
        <div class="layui-input-block">
          <input id="efe_name" type="text" name="name" lay-verify="required" lay-reqtext="必填项!" placeholder="不可重复" autocomplete="off" class="layui-input">
        </div>
      </div>
    </div>
    <div class="layui-form-item">
      <div class="layui-inline">
        <label class="layui-form-label layui-bg-green">生效时间</label>
        <div class="layui-input-inline">
          <input id="s_time"  type="text" name="s_time" lay-verify="required"  placeholder="开始时间" autocomplete="off" class="layui-input">
        </div>
      </div>
      <div class="layui-inline">
        <label class="layui-form-label layui-bg-green">结束时间</label>
        <div class="layui-input-inline">
          <input id="e_time"  type="text" name="e_time" lay-verify="required"  placeholder="结束时间" autocomplete="off" class="layui-input">
        </div>
      </div>
    </div>

    <div class="layui-form-item">
      <div class="layui-inline">
        <label class="layui-form-label layui-bg-green">报警类型</label>
        <div class="layui-input-block">
          <input type="radio" name="alarm_kind" value="in" title="进围栏报警" checked="">
          <input type="radio" name="alarm_kind" value="out" title="出围栏报警">
          <input type="radio" name="alarm_kind" value="all" title="进出围栏报警">
        </div>
      </div>
    </div>
    <div class="layui-form-item" style="display: none;">
      <div class="layui-inline">
        <label class="layui-form-label layui-bg-green">围栏类型</label>
        <div class="layui-input-inline">
          <input type="text" name="kind"  autocomplete="off" class="layui-input">
        </div>
      </div>
      <div class="layui-inline">
        <label class="layui-form-label layui-bg-green">围栏内容</label>
        <div class="layui-input-inline">
          <input type="text" name="content" autocomplete="off" class="layui-input">
        </div>
      </div>
    </div>
  <div id="efence_bind_dev" class="layui-transfer" style="padding: 10px"></div>
</form>

<!-- 围栏设置表格结束 -->

<script type="text/html" id="currentTableBar">
    <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>

<script type="text/javascript">

var dev_panle_sw=function(command){
  if(command=='hide'){
    $('#efence_list').hide()
    $('#show_sw').show()
  }else{
    $('#efence_list').show()
    $('#show_sw').hide()
  } 
}

var ajax_url='efence';

// 获取围栏数据，加载到围栏表格

var efence_table=function(data){

  map.clearOverlays()
  use_draw_tool()
  table.render({
    elem: '#efence_list_table',
    data: data,
    toolbar:'#draw_efence',
    id:'efence_list_table',
    skin:'nob',
    size:'sm',
    height: (get_height-60)/2-20,
    cols: [[
        {type: "checkbox", fixed: "left"},
        {field: 'name', title: '名称',sort:true},
        {field: 'kind', title: '类型',sort:true,
        templet: function(d){
              var efe_kind={'circle':'圆形围栏','polygon':'多边形围栏','rectangle':'矩形围栏'}
              return efe_kind[d.kind]
            }
          },
          {field: 'device_id', title: '绑定设备',sort:true},
          {title: '操作', minWidth: 110, templet: '#currentTableBar', fixed: "right", align: "center"}

          ]],
    // page: true,
    limit:100
  });
}

get_info_ajax(ajax_url,'get_init_data&map_kind=bd',efence_table)

// 、新建围栏按钮监听
table.on('toolbar(efence_list_table)',function(obj){
  map.clearOverlays()
  use_draw_tool()

})
// 重置围栏
$('#reset_efence').click(function(){
  map.clearOverlays()
  use_draw_tool()
})

//新建围栏功能，通过地图上画完围栏之后的回调函数实现该功能
var overlaycomplete = function(e){
  document.getElementById("handle_data_form").reset();
  transfer.reload('binded_dev', {
                  data: device
                  ,value:[]
                  ,title: ['未绑定', '绑定']
                  ,height:320
                  ,width:280
                  ,showSearch: true
                  ,parseData: function(res){
                    return {
                      "value": res.device_id //数据值
                      ,"title": '名称：'+res.user_name+'    ID:'+ res.device_id //数据标题
                      ,"disabled": ''  //是否禁用
                      ,"checked": '' //是否选中
                    }
                  }
  })
  form.render()
  var efencedata=new Array();
  map.clearOverlays();
  overlays=e.overlay;
  map.addOverlay(overlays);
  // overlays.addEventListener("click",efence_click);
  var p = e.overlay
  if(p instanceof BMap.Marker){
    alert(JSON.stringify(p.getPosition()));
  }else if(p instanceof BMap.Circle){
    efencedata.push(p.getRadius());
    efencedata.push(p.getCenter());
  }else{
    efencedata=p.getPath();
  };
  var efence_kind=e.target._drawingType

  layer.confirm("是否绘制完毕？",
                {btn: ['是', '重绘']}, 
                function (index) {
                                  layer.closeAll('dialog');
                                  $('#efe_name').removeAttr('readonly')
                                  layer.open({
                                    type: 1
                                    ,title:'电子围栏设置'
                                    ,area:['700px','650px']
                                    ,offset:'60px'  
                                    ,closeBtn:0
                                    ,id: 'efe_data_form' //防止重复弹出
                                    ,content:$('#handle_data_form')
                                    ,btn: ['提交','关闭']
                                    ,shade: 0 //不显示遮罩
                                    ,btn1: function(){
                                      var base_info=form.val('handle_data_form')
                                      if(base_info['name']==''){
                                        layer.msg('请输入围栏名称')
                                        return false
                                      }
                                      var binded_dev=transfer.getData('binded_dev');
                                      base_info['device_id']=[]
                                      for(var i=0;i<binded_dev.length;i++){
                                        base_info['device_id'].push(binded_dev[i]['value'])
                                      }
                                      base_info['content']=efencedata
                                      base_info['kind']=efence_kind
                                      if(base_info.s_time==''){
                                        base_info.s_time='0'
                                      }
                                      if(base_info.e_time==''){
                                        base_info.e_time='0'
                                      }
                                      
                                      // console.log(base_info)
                                      post_info_ajax(base_info,ajax_url,'add&map_kind=bd',efence_table)
                                    }
                                    ,btn2: function(){
                                      layer.closeAll();
                                      map.clearOverlays()
                                      use_draw_tool()
                                    }
                                  });

                                }, function(){
                                  map.clearOverlays()
                                  use_draw_tool()
                                });

};

// 电子围栏点击事件
var efence_click=function(efence_self){

  var efe_detail;
  var efe_name=efence_self.target.name
  document.getElementById("handle_data_form").reset();

  for(var i=0;i<ajax_get_info.length;i++){
    if(ajax_get_info[i]['name']==efe_name){
      efe_detail=ajax_get_info[i]
    }
  }

  form.val('handle_data_form',efe_detail)

  transfer.reload('binded_dev', {
                  data: device
                  ,value:eval(efe_detail['device_id'])
                  ,title: ['未绑定', '绑定']
                  ,height:320
                  ,width:280
                  ,showSearch: true
                  ,parseData: function(res){
                    return {
                      "value": res.device_id //数据值
                      ,"title": '名称：'+res.user_name+'    ID:'+ res.device_id //数据标题
                      ,"disabled": ''  //是否禁用
                      ,"checked": '' //是否选中
                    }
                  }
  })

  layer.open({
              type: 1
              ,title:'电子围栏详情'
              ,area:['700px','650px']
              ,offset:'60px'  
              ,id: 'efe_data_form' //防止重复弹出
              ,content:$('#handle_data_form')
              ,shade: 0 //不显示遮罩
            });

}



// 监听编辑按钮
table.on('tool(efence_list_table)',function(obj){
  var efe_detail=obj.data;
  if(obj.event=='del'){
    layer.confirm("确定删除围栏："+efe_detail.name+"？",
              {btn: ['是', '否']}, 
              function (index) {
                post_info_ajax(efe_detail,ajax_url,'del&map_kind=bd',efence_table)
              }
              ,function(){
                console.log('no')
                layer.closeAll()
              });
    return
  }
  $('#efe_name').attr('readonly','readonly')
  // console.log(obj)
  
  // 给表格赋值
  document.getElementById("handle_data_form").reset();
  if(efe_detail.s_time=='0'){
    efe_detail.s_time=''
  }
  if(efe_detail.e_time=='0'){
    efe_detail.e_time=''
  }
  form.val('handle_data_form',efe_detail)

  var org_bin_dev=eval(efe_detail['device_id'])
  transfer.reload('binded_dev', {
                  data: device
                  ,value:org_bin_dev
                  ,title: ['未绑定', '绑定']
                  ,height:320
                  ,width:280
                  ,showSearch: true
                  ,parseData: function(res){
                    return {
                      "value": res.device_id //数据值
                      ,"title": '名称：'+res.user_name+'    ID:'+ res.device_id //数据标题
                      ,"disabled": ''  //是否禁用
                      ,"checked": '' //是否选中
                    }
                  }
  })
  layer.open({
              type: 1
              ,title:'电子围栏设置'
              ,area:['700px','650px']
              ,offset:'60px'  
              ,closeBtn:0
              ,id: 'efe_data_form' //防止重复弹出
              ,content:$('#handle_data_form')
              ,btn: ['提交','关闭']
              ,shade: 0 //不显示遮罩
              ,btn1: function(){
                var base_info=form.val('handle_data_form')

                var binded_dev=transfer.getData('binded_dev');
                base_info['device_id']=[]
                for(var i=0;i<binded_dev.length;i++){
                  base_info['device_id'].push(binded_dev[i]['value'])
                }
                base_info['content']=eval(efe_detail.content)
                if(base_info.s_time==''){
                  base_info.s_time='0'
                }
                if(base_info.e_time==''){
                  base_info.e_time='0'
                }
                // console.log(base_info)
                post_info_ajax(base_info,ajax_url,'edit&map_kind=bd',efence_table)
              }
              ,btn2: function(){
                layer.closeAll();
                map.clearOverlays()
                use_draw_tool()
              }
            });
})

// 点击围栏列表，显示围栏内容
var checkDiv=new Array();
// 监听设备列表点击
table.on('row(efence_list_table)', function(obj){
 //选中行同步选中复选按钮
    var tr = obj.tr;
    var div = tr.find("div.layui-unselect");
    //checkDiv为定义的属性用来缓存当前点击的行是否选中状态，未选择的选中，选中的取消选中，并进行相应的地图打点处理
    // console.log(obj.data.device_id)
    if(!checkDiv[obj.data.name]) {
      checkDiv[obj.data.name] = obj;
      div.addClass("layui-form-checked");
      efence_show(obj.data)

    } else {
      div.removeClass("layui-form-checked");
      delete checkDiv[obj.data.name];
      efence_remove(obj.data.name)

    }

});

// 地图上展示围栏
var efence_show=function(row){
  var efencepath=row.content;
  efencepath=eval(efencepath);
  if(row.kind=='circle'){
    var efence_done=new BMap.Circle(efencepath[1],efencepath[0])
    efence_done.name=row.name

    map.addOverlay(efence_done);
    // 添加点击事件
    efence_done.addEventListener("click",efence_click);
  }else if(row.kind=='polygon' | row.kind=='rectangle'){
    var efence_done=new BMap.Polygon(efencepath)
    efence_done.name=row.name
    map.addOverlay(efence_done);
    // 添加点击事件
    efence_done.addEventListener("click",efence_click);
  }else if(row.kind=='polyline'){
    var polyline_points=new Array();
    for(var i=0;i<efencepath.length;i++){
      var p_p=new BMap.Point(efencepath[i]['lng'],efencepath[i]['lat'])
      polyline_points.push(p_p);

    }
    var efence_done=new BMap.Polyline(polyline_points)
    efence_done.name=row.name
    map.addOverlay(efence_done);
    // 添加点击事件
    efence_done.addEventListener("click",efence_click);
    var s_icon=new BMap.Icon("/static/images/start.png", new BMap.Size(100,60),{anchor : new BMap.Size(27, 13),imageSize:new BMap.Size(35, 30)});
    var e_icon=new BMap.Icon("/static/images/end.png", new BMap.Size(100,60),{anchor : new BMap.Size(27, 13),imageSize:new BMap.Size(35, 30)});
    var s_marker = new BMap.Marker(polyline_points[0],{icon:s_icon});
    var e_marker= new BMap.Marker(polyline_points[polyline_points.length-1],{icon:e_icon});
    map.addOverlay(s_marker);
    map.addOverlay(e_marker);
  }
  var efencelng=efencepath[1]['lng'];
  var efencelat=efencepath[1]['lat'];
  var efencepoint=new BMap.Point(efencelng,efencelat);
  map.panTo(efencepoint);
}

//删除地图上面显示的指定围栏
var efence_remove=function(efence_name){
  var fugaiwu = map.getOverlays();
  for(var i=0,n=fugaiwu.length;i<n;i++){
    if (fugaiwu[i].name==efence_name) {
      map.removeOverlay(fugaiwu[i]); 
      return false;
    };
  };
};

//百度地图调用相关
var map = new BMap.Map("allmap");    // 创建Map实例
  map.centerAndZoom(new BMap.Point(114.404, 22.815), 12);  // 初始化地图,设置中心点坐标和地图级别
  //添加地图类型控件
  map.addControl(new BMap.MapTypeControl({
    mapTypes:[
            BMAP_NORMAL_MAP,
            BMAP_HYBRID_MAP
        ]}));   
  map.setCurrentCity("深圳");          // 设置地图显示的城市 此项是必须设置的
  map.enableScrollWheelZoom(true);

 var styleOptions = {
        strokeColor:"blue",    //边线颜色。
        fillColor:"blue",      //填充颜色。当参数为空时，圆形将没有填充效果。
        strokeWeight: 5,       //边线的宽度，以像素为单位。
        strokeOpacity: 0.8,    //边线透明度，取值范围0 - 1。
        fillOpacity: 0.2,      //填充的透明度，取值范围0 - 1。
        strokeStyle: 'solid' //边线的样式，solid或dashed。
    }
//实例化鼠标绘制工具
var use_draw_tool=function(){
  var draw_tool = new BMapLib.DrawingManager(map, {
    isOpen: false, //是否开启绘制模式
    enableDrawingTool: true, //是否显示工具栏
    drawingToolOptions: {
        anchor: BMAP_ANCHOR_TOP_RIGHT, //位置
        offset: new BMap.Size(110, 10), //偏离值
        drawingModes : [
        BMAP_DRAWING_CIRCLE,
        BMAP_DRAWING_POLYGON,
        BMAP_DRAWING_RECTANGLE 
     ]
    },
    circleOptions: styleOptions, //圆的样式
    polygonOptions: styleOptions, //多边形的样式
    rectangleOptions: styleOptions //矩形的样式
  });  

  draw_tool.addEventListener('overlaycomplete', overlaycomplete);
}

use_draw_tool()

//穿梭框渲染
var efence_bind_dev=transfer.render({
  elem: '#efence_bind_dev'
  ,id:'binded_dev'
  ,data: device
  ,title: ['未绑定', '绑定']
  ,height:320
  ,showSearch: true
  ,parseData: function(res){
    return {
      "value": res.device_id //数据值
      ,"title": '名称：'+res.user_name+'ID:'+ res.device_id//数据标题
      ,"disabled": ''  //是否禁用
      ,"checked": '' //是否选中
    }
  }
})

// 时间框渲染
laydate.render({
  elem: '#s_time'
  ,type: 'datetime'
  // ,value:new Date(new Date(new Date().toLocaleDateString()).getTime())
  ,btns: ['clear','now', 'confirm']
});

laydate.render({
  elem: '#e_time'
  ,type: 'datetime'
  // ,value:new Date()
  ,btns: ['clear','now', 'confirm']
});


// 监听围栏搜索操作
form.on('submit(data-search-btn)', function (data) {

  var search_key = data.field['search_key'];
  if(search_key!==''){
    // 调用index页面搜索函数
    var search_result=search_func(ajax_get_info,search_key,'name','kind')
    // 表格重载
    efence_table(search_result)
  }else{
    efence_table(ajax_get_info)
  }
  return false;
});

// 监听指定设备的围栏搜索操作
form.on('submit(dev-efe-search-btn)', function (data) {

  var search_key = data.field['search_key'];
  if(search_key!==''){
    // 调用index页面搜索函数
    var search_result=search_func(device,search_key,'device_id','user_name')
    // 表格重载
    console.log(search_result,ajax_get_info)
    if(search_result[0]['efence']=='0'){
      efence_of_dev_table([])
    }else{
      search_result=search_result[0]['efence']
      var show_data=[];
      var efe_name_list=[]
      for(var k in search_result){
        efe_name_list.push(search_result[k].name)
      }
      for (var i = ajax_get_info.length - 1; i >= 0; i--) {
        if(efe_name_list.indexOf(ajax_get_info[i].name)!=-1){
          show_data.push(ajax_get_info[i])
        }
      }
      efence_of_dev_table(show_data)
    }

    }else{
      efence_of_dev_table([])
    }
    return false;
});

// 根据设备id，查找设备绑定的围栏详情
var efence_of_dev_table=function(data){
table.render({
  elem: '#efence_of_dev_table',
  data: data,
  // toolbar:'#draw_efence',
  id:'efence_of_dev_table',
  skin:'nob',
  size:'sm',
  height: (get_height-60)/3,
  cols: [[
      {type: "checkbox", fixed: "left"},
      {field: 'name', title: '名称',sort:true},
      {field: 'kind', title: '类型',sort:true,
        templet: function(d){
            console.log(d)
            var efe_kind={'circle':'圆形围栏','polygon':'多边形围栏','rectangle':'矩形围栏'}
            return efe_kind[d.kind]
          }
        },
        {field: 'alarm_kind', title: '报警类型',sort:true,
          templet: function(d){
            var alarm_kind_dict={'in':'进围栏报警','out':'出围栏报警','all':'进出围栏报警'}
            return alarm_kind_dict[d.alarm_kind]
          }
        },
        {field: 'time', title: '生效时间',sort:true,
          templet: function(d){
            var effect_time=d.s_time+'--'+d.e_time
            return effect_time
          }
        }
        // {title: '操作', minWidth: 110, templet: '#currentTableBar', fixed: "right", align: "center"}

        ]],
  // page: true,
  limit:100
});

}
efence_of_dev_table([])

// 点击围栏列表，显示围栏内容
var checkefe=new Array();
// 监听设备列表点击
table.on('row(efence_of_dev_table)', function(obj){
 //选中行同步选中复选按钮
    var tr = obj.tr;
    var div = tr.find("div.layui-unselect");
    //checkDiv为定义的属性用来缓存当前点击的行是否选中状态，未选择的选中，选中的取消选中，并进行相应的地图打点处理
    // console.log(obj.data.device_id)
    if(!checkefe[obj.data.name]) {
      checkefe[obj.data.name] = obj;
      div.addClass("layui-form-checked");
      efence_show(obj.data)

    } else {
      div.removeClass("layui-form-checked");
      delete checkefe[obj.data.name];
      efence_remove(obj.data.name)

    }

});

// 百度地图地址搜索功能
var local = new BMap.LocalSearch(map, {
    renderOptions:{map: map}
  });
var search_map=function(addr){
  console.log(addr)
  local.search(addr);
}

</script>
